<?php

//verify post and required fields to move to update status and posts
       try {
        $executionResult=array();
        $loggedInId=0;
        $parentid=0;
        $postedTitle="";
        $postedContent="";
        $shareadditionalmsg="";
        $sharedPostwithtypeid=0;
        $clusteredId=0;
        $sharedPostid=0;
        $posttypeId=0;
        $postparentid=0;
        $postlocation="";
        $taggedinUsers="";
        $postAction = new PostAction();
        $privSettings = PrivacySettings::DefaultSetting;
        $postTypeRead=PostType::Status_Updates;
        $postMedias="";
        $emotionstextstr="";
        
        //try to read all psted values
        if (isset($_SESSION["Allyfolio_User_ID"]) && !empty($_SESSION["Allyfolio_User_ID"])) {
            $loggedInId = trim($_SESSION["Allyfolio_User_ID"]);
        }
        
        //post title, content, and parent id
        if (isset($_POST["Post"]["Parent_ID"]) && !empty($_POST["Post"]["Parent_ID"])) {
            $parentid = trim($_POST["Post"]["Parent_ID"]);
        } 
        if(isset($_POST["Post"]["post_title"]) && !empty($_POST["Post"]["post_title"])){
            $postedTitle=trim($_POST["Post"]["post_title"]);
        }        

        if(isset($_POST["Post"]["post_content"]) && !empty($_POST["Post"]["post_content"])){
            $postedContent = trim($_POST["Post"]["post_content"]);
        }
        else if (isset($_POST["sStatus"]) && !empty($_POST["sStatus"])) {
            $postedContent = trim($_POST["sStatus"]);
        }
        if (isset($_POST["emotionstext"]) && !empty($_POST["emotionstext"])) {
            $emotionstextstr = trim($_POST["emotionstext"]);
        }
                
        //post type
        if (isset($_POST["nPostType"]) && !empty($_POST["nPostType"]) && is_numeric(trim($_POST["nPostType"]))) {
            $postTypeRead = trim($_POST["nPostType"]);
        }
        
        if(isset($_POST["share_with_options"]) && !empty($_POST["share_with_options"])){
            $sharedPostwithtypeid=trim($_POST["share_with_options"]);
        }
        if(isset($_POST["share_with_cluster"]) && !empty($_POST["share_with_cluster"])){
            $clusteredId=trim($_POST["share_with_cluster"]);
        }
        
        if(isset($_POST["post_shared_id"]) && !empty($_POST["post_shared_id"])){
            $sharedPostid=trim($_POST["post_shared_id"]);
        }
        if(isset($_POST["post_share_msg"]) && !empty($_POST["post_share_msg"])){
            $shareadditionalmsg=trim($_POST["post_share_msg"]);
        }
        if(isset($_POST["post_location"]) && !empty($_POST["post_location"])){
            $postlocation=trim($_POST["post_location"]);
        }
        if(isset($_POST["taggedinUsers"]) && !empty($_POST["taggedinUsers"])){
            $taggedinUsers=trim($_POST["taggedinUsers"]);
        }
        if(isset($_POST["postMedias"]) && !empty($_POST["postMedias"])){
            $postMedias=substr(trim($_POST["postMedias"]),0,strlen(trim($_POST["postMedias"]))-1);
        }
        
        //echo "userid:".$loggedInId."<br> parent id: ".$parentid."<br> title:".$postedTitle."<br> content: ".$postedContent."<br> Type: ".$postTypeRead;
        //Post Uploads
        $imgdatastr="";
        $hasFile=false;
        $fileType="";
        if (isset($_FILES["imgdata"]) && $_FILES["imgdata"]["error"]==0 && $_FILES["imgdata"]["size"]>0) {
            $hasFile=true;
            $fileType=$_FILES["imgdata"]["type"];
        }
        
        //user privacy setings
        if (!empty($_SESSION['user_settings']['privacy_settings'])) {
            $privSettings = trim($_SESSION['user_settings']['privacy_settings']);
        }
        
        //validate if required parameters found or not, if not then die with error codes
        if (!is_numeric($loggedInId)) {
            die(responseWithErrorCode($postAction->Failed_For_Invalid_Session["err_code"],$postAction->Failed_For_Invalid_Session["msg"]));
        }
        
        //if action type is of sharing type then fetch shared post content
        switch ($postTypeRead) {
            case PostType::Share:
                //code to fetch post details
                $objReadNewsFeed= new ReadFeedAction();
                $postDetails=$objReadNewsFeed->getPostSnapshotDetails($sharedPostid,$postTypeRead,$parentid,$clusteredId);
                
                if(is_array($postDetails) && count($postDetails)>0){
                    $postDetails=$postDetails[0];
                    
                    $postedTitle=$postDetails["Post_Title"];
                    $postedContent=$postDetails["PostedContent"];
                    //$postTypeRead=$postDetails["Post_Type_ID"];
                    $parentid=$postDetails["Parent_ID"];
                    $sourceId=$postDetails["Source_ID"];
                }
                
                break; 
        }
        
        if (trim($postedContent) == "") {
            die(responseWithErrorCode($postAction->Failed_For_Content["err_code"],$postAction->Failed_For_Content["msg"]));
        }
        if (is_numeric($privSettings) && $privSettings <= 0) {
            die(responseWithErrorCode($postAction->Failed_For_Invalid_Privacy_Settings["err_code"],$postAction->Failed_For_Invalid_Privacy_Settings["msg"]));
        }
        
        if(!isset($parentid) || !is_numeric($parentid)){
            $parentid=0;
        }
        
        //verify and move forward to submit post or status
        if(!empty($postedContent) && $loggedInId>0 && $postTypeRead>0 && $privSettings>0){
            $PerformPostAction = new PerformPostAction();
            $actionRes = $PerformPostAction->PostData(
                                                        $postedTitle,
                                                        $postedContent, 
                                                        $loggedInId, 
                                                        $postTypeRead, 
                                                        $privSettings,
                                                        $parentid,
                                                        $clusteredId,
                                                        $sharedPostid,
                                                        $shareadditionalmsg,
                                                        $sharedPostwithtypeid,
                                                        $postlocation,
                                                        $taggedinUsers,
                                                        $postMedias,
                                                        $emotionstextstr
                                                      );
            //echo "<br>--> stope post data -->";                                              
            //print_r($actionRes);
            switch ($postTypeRead) {
                case PostType::Status_Updates:
                    //handle cases
                    switch ($actionRes["err_code"]) {
                        case $postAction->Success["err_code"]:
                            $isFileUploaded=false;
                            if($hasFile){
                                if ((($fileType == "image/gif")
                                        || ($fileType == "image/jpeg")
                                        || ($fileType == "image/jpg")
                                        || ($fileType == "image/pjpeg")
                                        || ($fileType == "image/x-png")
                                        || ($fileType == "image/png"))
                                    )
                                {
                                    $isFileUploaded=uploadFile($PerformPostAction->lastInsertedID,"IMAGE");        
                                        
                                }
                                else{
                                    $isFileUploaded=uploadFile($PerformPostAction->lastInsertedID,"VIDEO");
                                }
                            }
                            if($isFileUploaded){
                                $executionResult=$actionRes;
                                die(responseWithErrorCode($actionRes["err_code"],$actionRes["msg"]));
                            }
                            else{
                                $executionResult=$actionRes;
                                die(responseWithErrorCode($actionRes["err_code"],$actionRes["msg"]));
                            }
                            break;
        
                        case $postAction->Failure["err_code"]:
                            $executionResult=$actionRes;
                            die(responseWithErrorCode($actionRes["err_code"],$actionRes["msg"]));
                            break;
                    }
        
                    break;
                case PostType::Share:
                    //handle cases
                    switch ($actionRes["err_code"]) {
                        case $postAction->Success["err_code"]:
                            $executionResult=$actionRes;
                            die(responseWithErrorCode($actionRes["err_code"],$actionRes["msg"]));
                            break;
        
                        case $postAction->Failure["err_code"]:
                            $executionResult=$actionRes;
                            die(responseWithErrorCode($actionRes["err_code"],$actionRes["msg"]));
                            break;
                    }
                    break;    
                case PostType::Wall_Post:
                    //handle cases
                    switch ($actionRes["err_code"]) {
                        case $postAction->Success["err_code"]:
                            $executionResult=$actionRes;
                            die(responseWithErrorCode($actionRes["err_code"],$actionRes["msg"]));
                            break;
        
                        case $postAction->Failure["err_code"]:
                            $executionResult=$actionRes;
                            die(responseWithErrorCode($actionRes["err_code"],$actionRes["msg"]));
                            break;
                    }
                    break;
                case PostType::Technopath:
                    //handle cases
                    $isFileUploaded=false;
                    if($hasFile){
                        if ((($fileType == "image/gif")
                                || ($fileType == "image/jpeg")
                                || ($fileType == "image/jpg")
                                || ($fileType == "image/pjpeg")
                                || ($fileType == "image/x-png")
                                || ($fileType == "image/png"))
                            )
                        {
                            $isFileUploaded=uploadFile($PerformPostAction->lastInsertedID,"IMAGE");        
                                
                        }
                        else{
                            $isFileUploaded=uploadFile($PerformPostAction->lastInsertedID,"VIDEO");
                        }
                    }
                    if($isFileUploaded){
                        $executionResult=$actionRes;
                        //die(responseWithErrorCode($actionRes["err_code"],$actionRes["msg"]));
                    }
                    else{
                        $executionResult=$actionRes;
                        //die(responseWithErrorCode($actionRes["err_code"],$actionRes["msg"]));
                    }
                    break;
                case PostType::Pages:
                    //handle cases
                    switch ($actionRes["err_code"]) {
                        case $postAction->Success["err_code"]:
                            $isFileUploaded=false;
                            if($hasFile){
                                if ((($fileType == "image/gif")
                                        || ($fileType == "image/jpeg")
                                        || ($fileType == "image/jpg")
                                        || ($fileType == "image/pjpeg")
                                        || ($fileType == "image/x-png")
                                        || ($fileType == "image/png"))
                                    )
                                {
                                    $isFileUploaded=uploadFile($PerformPostAction->lastInsertedID,"IMAGE");        
                                        
                                }
                                else{
                                    $isFileUploaded=uploadFile($PerformPostAction->lastInsertedID,"VIDEO");
                                }
                            }
                            if($isFileUploaded){
                                $executionResult=$actionRes;
                                die(responseWithErrorCode($actionRes["err_code"],$actionRes["msg"]));
                            }
                            else{
                                $executionResult=$actionRes;
                                die(responseWithErrorCode($actionRes["err_code"],$actionRes["msg"]));
                            }
                            break;
        
                        case $postAction->Failure["err_code"]:
                            $executionResult=$actionRes;
                            die(responseWithErrorCode($actionRes["err_code"],$actionRes["msg"]));
                            break;
                    }
        
                    break;
            }
        
        }
    }
    catch (exception $ex) {
        die('post_script_src.php: validating posted parameters():: \t' . $ex->getMessage() ."\n");
    }
    
    
/* ############################ SUPPORTIVE FUNCTIONS #######################*/
 
function uploadFile($postid,$mediaType="IMAGE"){
    $filereturnpath="";
    $actionRes=array();
    try{
        if (isset($_FILES["imgdata"]) && $_FILES["imgdata"]["error"]==0) {
            $hasFile=true;
            $isPathExist=true;
            $isFileExist=false;
            $isFileUploaded=false;
            $allowedExts = array("gif", "jpeg", "jpg", "png");
            
            $temp = explode(".", $_FILES["imgdata"]["name"]);
            $extension = end($temp);
            if ((($_FILES["imgdata"]["type"] == "image/gif")
                    || ($_FILES["imgdata"]["type"] == "image/jpeg")
                    || ($_FILES["imgdata"]["type"] == "image/jpg")
                    || ($_FILES["imgdata"]["type"] == "image/pjpeg")
                    || ($_FILES["imgdata"]["type"] == "image/x-png")
                    || ($_FILES["imgdata"]["type"] == "image/png"))
                    //&& ($_FILES["imgdata"]["size"] < 20000)
                    && in_array($extension, $allowedExts)) 
            {
              
                  if ($_FILES["imgdata"]["error"] > 0) {
                        echo $_FILES["imgdata"]["error"];
                  } 
                  else 
                  {
                        //echo "Upload: " . $_FILES["imgdata"]["name"] . "<br>";
//                        echo "Type: " . $_FILES["imgdata"]["type"] . "<br>";
//                        echo "Size: " . ($_FILES["imgdata"]["size"] / 1024) . " kB<br>";
//                        echo "Temp file: " . $_FILES["imgdata"]["tmp_name"] . "<br>";
                        $filepath="uploads/postuploads/images/";
                        $uploadPath=$_SERVER['DOCUMENT_ROOT']."/".$filepath;
                        // To create the nested structure, the $recursive parameter 
                        // to mkdir() must be specified.
                        
                        if(!file_exists($uploadPath)){
                            $isPathExist=false;
                            if (!mkdir($uploadPath, 0777, true)) {
                                $isPathExist=false;
                            }
                            else{
                                $isPathExist=true;
                            }    
                        }
                        
                        $filename=strtotime(date("Y-m-d H:i:s"))."_".str_replace(" ","_",$_FILES["imgdata"]["name"]);
                        if ($isPathExist==true && file_exists($uploadPath. $filename)) {
                           $isFileExist=true;
                        } 
                        else 
                        {
                            
                            if(move_uploaded_file($_FILES["imgdata"]["tmp_name"],$uploadPath.$filename)){
                                $filereturnpath=$filepath.$filename;
                                $isFileUploaded=true;
                            }
                            else{
                                $isFileUploaded=false;
                            }
                        }
                  }
            } 
            else {
              $isFileUploaded=false;
            }
        }
        if($isFileUploaded){
            $PerformPostAction = new PerformPostAction();
            $actionRes = $PerformPostAction->UploadPostMedia(
                                                    $postid,
                                                    $filereturnpath, 
                                                    $mediaType
                                                    );
        }
    }
    catch(Exception $ex){
        
    }
    if(is_array($actionRes) && count($actionRes)>0 && $actionRes["err_code"]==200 && $filereturnpath!="" && strstr($filereturnpath,".")){
        return true;
    }
    else{
        return false;
    }
}
?>